import React from "react";
import ReactDOM from "react-dom/client";

let zIndex = 1000;
let id = 0;
let pool = new Map<number, HTMLDivElement>();

export type DialogOptions = {
  /** 宽度 */
  width?: number,
  /** 高度 */
  height?: number,
  /** 是否可以通过点击遮罩层关闭 */
  escByClickModel?: boolean,
}

export default () => {
  return {
    open: (children: React.ReactElement, options: DialogOptions = {}) => {
      const {width = 300, height = 300, escByClickModel = true} = options;
      const dialog = document.createElement('div');
      const _id = id ++;
      const close = () => {
        document.body.removeChild(dialog);
        pool.delete(_id);
      }

      // TODO: style
      dialog.className = "";
      dialog.style.zIndex = String(zIndex++);
      dialog.onclick = () => escByClickModel ? close() : null;

      const dialogContent = document.createElement('div')
      // TODO: style
      dialogContent.className = ""
      dialogContent.style.width = `${width}px`
      dialogContent.style.height = `${height}px`

      // const dom = document.createElement('div')
      // dialogContent.appendChild(dom)

      dialog.appendChild(dialogContent);
      document.body.appendChild(dialog);
      dialogContent.onclick = event => {
        event.stopPropagation()
        // @ts-ignore
        // if (event.target.classList.contains('get')) close()
      };

      const root = ReactDOM.createRoot(dialogContent);
      root.render(children);
      pool.set(_id, dialog);
      return { close }
    },
    close(_id?: number) {
      if (_id) {
        const dialog = pool.get(_id);
        if (dialog) {
          document.body.removeChild(dialog);
          pool.delete(_id);
        }
      } else {
        for (const [key, value] of pool) {
          document.body.removeChild(value);
          pool.delete(key);
        }
      }
    }
  }
}